package com.example.java8;

import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DependencyAnalyzer {
    public static void main(String[] args) throws FileNotFoundException {

        CompilationUnit cu = StaticJavaParser.parse(new FileInputStream("/Users/xiaohongfei/learnCode/technology-share" +
                "/jdk8/src/main/java/com/example/java8/StreamTest.java"));
        DependencyVisitor visitor = new DependencyVisitor();
        visitor.visit(cu, null);
        Map<String, List<String>> dependencies = visitor.getDependencies();
        System.out.println(dependencies);
    }

    private static class DependencyVisitor extends VoidVisitorAdapter<Void> {
        private Map<String, List<String>> dependencies = new HashMap<>();
        private String currentClass;

        @Override
        public void visit(ClassOrInterfaceDeclaration n, Void arg) {
            currentClass = n.getNameAsString();
            dependencies.put(currentClass, new ArrayList<>());
            super.visit(n, arg);
        }

        @Override
        public void visit(MethodDeclaration n, Void arg) {
            super.visit(n, arg);
            String currentMethod = n.getNameAsString();
            List<MethodCallExpr> methodCalls = n.findAll(MethodCallExpr.class);
            for (MethodCallExpr methodCall : methodCalls) {
                String methodName = methodCall.getNameAsString();
                String className = methodCall.getScope().map(expr -> expr.toString()).orElse(currentClass);
                dependencies.computeIfAbsent(currentClass, k -> new ArrayList<>()).add(className);
            }
        }

        public Map<String, List<String>> getDependencies() {
            return dependencies;
        }
    }
}